package cn.edu.gdut.deepcode.controller;

import cn.edu.gdut.deepcode.constant.ReqRespConstant;
import cn.edu.gdut.deepcode.domain.dto.UserDTO;
import cn.edu.gdut.deepcode.domain.po.Result;
import cn.edu.gdut.deepcode.domain.vo.UserVO;
import cn.edu.gdut.deepcode.service.IUserService;
import cn.edu.gdut.deepcode.utils.CommonUtils;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import io.swagger.annotations.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

import static cn.edu.gdut.deepcode.constant.AbnormalInfoConstant.UL_USER_EI_2;
import static cn.edu.gdut.deepcode.constant.ReqRespConstant.AUTHORIZATION_HEADER_NAME;

/**
 * <p>
 * 登录接口
 * </p>
 *
 * @Author: 暮倦
 * @Since: 2025-04-08  21:04
 * @Version: 1.0.0
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/api")
@Api("登录注册接口组")
public class LoginController {

    private final IUserService userService;
    @ApiOperation("用户登录接口")
    @ApiResponses(@ApiResponse(code = ReqRespConstant.SUCCESSFUL_CODE,
            message= ReqRespConstant.COMMON_SUCCESSFUL_MSG,
            responseHeaders = @ResponseHeader(
                    name=AUTHORIZATION_HEADER_NAME,
                    description = "token(内含用户id),每次请求需携带在Authorization头中",
                    response =String.class)))
    @PostMapping("/login/users")
    public Result<UserVO> login(@RequestBody UserDTO userDTO, HttpServletResponse response){
        if (BeanUtil.isEmpty(userDTO)){
            CommonUtils.recordErrorInfoAndThrowException(
                    UL_USER_EI_2,userDTO);
        }
        if (StrUtil.isBlank(userDTO.getUsername())||StrUtil.isBlank(userDTO.getPassword())){
            CommonUtils.recordErrorInfoAndThrowException(UL_USER_EI_2,userDTO);
        }
        return userService.login(userDTO,response);
    }

    @ApiOperation(value = "用户注册接口",notes = "响应体中的data属性为null")
    @PostMapping("/register/users")
    public Result<?> register(@RequestBody UserDTO userDTO){
        if (BeanUtil.isEmpty(userDTO)){
            CommonUtils.recordErrorInfoAndThrowException(UL_USER_EI_2,userDTO);
        }
        if (StrUtil.isBlank(userDTO.getUsername())||StrUtil.isBlank(userDTO.getPassword())){
            CommonUtils.recordErrorInfoAndThrowException(UL_USER_EI_2,userDTO);
        }
        if (userDTO.getPassword().length()>18||userDTO.getUsername().length()>18){
            CommonUtils.recordErrorInfoAndThrowException(UL_USER_EI_2,userDTO);
        }
        return userService.register(userDTO);
    }
}


